import {Base} from '../../utils/base.js';
import {Config} from '../../utils/config.js';

class Address extends Base{
  constructor(){
    super();
  }

  /*
    *根据省市县信息组装地址信息
    * provinceName , province 前者为 微信选择控件返回结果，后者为查询地址时，自己服务器后台返回结果
    */
   setAddressInfo(res){
    var province =res.provinceName || res.province,
        city =res.cityName || res.city,
        country =res.countyName || res.country,
        detail =res.detailInfo || res.detail;
    var totalDetail=city+country+detail;

    //直辖市，取出省部分
    if(!this.isCenterCity(province)) {
        totalDetail=province+totalDetail;
    };
    return totalDetail;
  }

  /**
   * 是否为直辖市
   * @param {*} name 
   */
  isCenterCity(name) {
    var centerCitys=['北京市','天津市','上海市','重庆市'],
        flag=centerCitys.indexOf(name) >= 0;
    return flag;
  }

    /**
   * 获取用户地址
   */
  getUserAddressInfo(callback) {
    var that = this;
    var params = {
      url:'address/user_address',
      sCallback:function(res){
        var addressInfo = res.data;
        if (addressInfo){
          addressInfo.totalDetail = that.setAddressInfo(addressInfo);
          callback && callback(addressInfo)
        }
      }
    };
    this.request(params);
  }

  /**
   * 更新保存地址
   * @param {*} data 
   * @param {*} callback 
   */
  submitAddress(data,callback){
    data = this._setUpAddress(data);

    var param={
        url: 'address/edit',
        type:'post',
        data:data,
        sCallback:function(res){
            callback && callback(true,res);
        },eCallback(res){
            callback && callback(false,res);
        }
    };
    this.request(param);
  }

  /**
   * 整理保存的地址数据
   * @param {*} res 
   * @param {*} callback 
   */
  _setUpAddress(res,callback){
    var formData={
            name:res.userName,
            province:res.provinceName,
            city:res.cityName,
            country:res.countyName,
            mobile:res.telNumber,
            detail:res.detailInfo
        };
    return formData;
  }
}

export {Address};